package com.itany.boot.nmms.service.impl;

import com.itany.boot.nmms.constant.DistinctConstant;
import com.itany.boot.nmms.dao.ProductMapper;
import com.itany.boot.nmms.dao.SequenceMapper;
import com.itany.boot.nmms.entity.Product;
import com.itany.boot.nmms.entity.ProductExample;
import com.itany.boot.nmms.entity.Sequence;
import com.itany.boot.nmms.entity.SequenceExample;
import com.itany.boot.nmms.exception.GetSerialNoException;
import com.itany.boot.nmms.exception.ProductExistsException;
import com.itany.boot.nmms.exception.RequestParamsException;
import com.itany.boot.nmms.service.ProductService;
import com.itany.boot.nmms.util.ParamsUtil;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private SequenceMapper sequenceMapper;

    @Override
    public void add(String name, String price, String productType, MultipartFile file, HttpSession session) throws RequestParamsException, FileUploadException, GetSerialNoException, ProductExistsException {
        if (ParamsUtil.isNull(name) || ParamsUtil.isNull(price) || ParamsUtil.isNull(productType) || file.isEmpty()) {
            throw new RequestParamsException("请求参数有误");
        }

        ProductExample productExample = new ProductExample();
        productExample.or()
                .andProductTypeIdEqualTo(Integer.valueOf(productType))
                .andNameEqualTo(name);
        List<Product> products = productMapper.selectByExample(productExample);
        if (!products.isEmpty()) {
            throw new ProductExistsException("该商品已存在");
        }

        Product product = new Product();
        product.setName(name);
        product.setPrice(Double.valueOf(price));
        product.setProductTypeId(Integer.valueOf(productType));

        SequenceExample example = new SequenceExample();
        example.or()
                .andNameEqualTo(DistinctConstant.PRODUCT_PREFIX);
        List<Sequence> sequences = sequenceMapper.selectByExample(example);
        //生成产品编号
        //查找数据库中是否有对应的序列号
        //数据库中不存在对应序列号
        //设置初始值，执行添加操作
        if (sequences.isEmpty()) {
            Sequence sequence = new Sequence();
            sequence.setName(DistinctConstant.PRODUCT_PREFIX);
            sequence.setValue(DistinctConstant.PRODUCT_SERIAL__INIT_VALUE);
            sequenceMapper.insert(sequence);
            product.setProductNo(DistinctConstant.PRODUCT_PREFIX + new SimpleDateFormat("yyyyMMdd").format(new Date()) + sequence.getValue());
        } else {
            //若不是第一次则，数据库中存在对应序列号
            //
            //不大于最大值，执行+1，大于则设置默认，执行修改
            Sequence sequence = sequences.get(0);
            if (sequence.getValue().equals(DistinctConstant.PRODUCT_SERIAL__MAx_VALUE)) {
                sequence.setValue(DistinctConstant.PRODUCT_SERIAL__INIT_VALUE);
            } else {
                sequence.setValue(String.format("%05d", Integer.parseInt(sequence.getValue())+1));
            }

            sequenceMapper.updateByPrimaryKeySelective(sequence);
            product.setProductNo(DistinctConstant.PRODUCT_PREFIX + new SimpleDateFormat("yyyyMMdd").format(new Date()) + sequence.getValue());

        }

        //上传图片
        String realPath = DistinctConstant.PRODUCT_ROOT_DIRECTORY + new SimpleDateFormat("yyyyMMdd").format(new Date());
        try {
            String path = ResourceUtils.getURL("classpath:").getPath() + realPath;
            File f = new File(path);
            f.mkdirs();
            String filename = file.getOriginalFilename();
            filename = filename.substring(0, filename.lastIndexOf(".")) + "-" + System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
            String image = realPath + "/" + filename;
            //添加图片
            product.setImage(image);
            productMapper.insertSelective(product);
            //上传图片
            file.transferTo(new File(path, filename));
        } catch (IOException e) {
            throw new FileUploadException("文件上传错误");
        }





    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<Product> findAll() {
        List<Product> products = productMapper.selectAll();
        return products.isEmpty() ? null : products;
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public Product findById(String id) throws RequestParamsException {
        if (ParamsUtil.isNull(id)) {
            throw new RequestParamsException("请求参数异常");
        }
        Product product = productMapper.selectById(Integer.valueOf(id));
        return product;
    }

    @Override
    public void update(String id, String name, String price, String productType, MultipartFile file, HttpSession session) throws RequestParamsException, ProductExistsException, FileUploadException {
        if (ParamsUtil.isNull(name) || ParamsUtil.isNull(price) || ParamsUtil.isNull(productType)) {
            throw new RequestParamsException("请求参数有误");
        }
        ProductExample example = new ProductExample();
        example.or()
                .andProductIdNotEqualTo(Integer.valueOf(id))
                .andProductTypeIdEqualTo(Integer.valueOf(productType))
                .andNameEqualTo(name);
        List<Product> products = productMapper.selectByExample(example);
        if (!products.isEmpty()) {
            throw new ProductExistsException("该商品已存在");
        }
        Product product = new Product();
        product.setProductId(Integer.valueOf(id));
        product.setName(name);
        product.setPrice(Double.valueOf(price));
        product.setProductTypeId(Integer.valueOf(productType));

        //修改图片,若存在则修改，不存在则不执行
        System.out.println("文件大小:" + file.isEmpty());
        if (!file.isEmpty()) {
            try {
                String realPath = DistinctConstant.PRODUCT_ROOT_DIRECTORY + new SimpleDateFormat("yyyyMMdd").format(new Date());
                String path = ResourceUtils.getURL("classpath:").getPath() + realPath;
                File f = new File(path);
                f.mkdirs();

                String filename = file.getOriginalFilename();
                filename = filename.substring(0, filename.lastIndexOf(".")) + "-" + System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
                String image = realPath+ "/" + filename;
                file.transferTo(new File(path, filename));
                product.setImage(image);
            } catch (IOException e) {
                throw new FileUploadException("文件上传错误");
            }
        }

        productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    public void removeById(String id) throws RequestParamsException {
        if (ParamsUtil.isNull(id)) {
            throw new RequestParamsException("请求参数有误");
        }

        productMapper.deleteByPrimaryKey(Integer.valueOf(id));
    }
}
